package twice.class03_quicksort;

public class Class01_QuickSort {
    // 荷兰国旗问题
    //以最右的数为划分
    public static int[] netherlandsFlag(int[] arr, int L, int R) {
        if(L>R){return new int[]{-1,-1};}
        if(L==R){return new int[]{L,R};}
        int less = L-1;
        int more = R;
        int index = L;
        while(index < more){
            if (arr[index] == arr[R]) {
                index++;
            }else if(arr[index] < arr[R]){
                swap(arr,++less,index++);
            }else if(arr[index] > arr[R]){
                swap(arr,index,--more);
            }

        }
        swap(arr,R,more);
        return new int[]{less+1,more};
    }
    public static void quickSort1(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        process(arr, 0, arr.length - 1);
    }

    public static void process(int[] arr, int L, int R) {
        if (L >= R) {
            return;
        }
        swap(arr, L + (int) (Math.random() * (R - L + 1)), R);
        int[] equalArea = netherlandsFlag(arr, L, R);
        process(arr, L, equalArea[0] - 1);
        process(arr, equalArea[1] + 1, R);
    }

    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
    public static void main(String[] args) {
        int[] arr = new int[]{8,7,5,2,6,4,3,1,9,3,9,3};
        quickSort1(arr);
        for (int i : arr) {
            System.out.print(i);
        }
    }

}
